<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html" ; charset="utf-8" />
    <title>老师管理</title>
    <link href="../../../css/main.css" rel="stylesheet" type="text/css" />
    <link
      href="../../../bstable/css/bootstrap.min.css"
      rel="stylesheet"
      type="text/css"
    />
    <link
      href="../../../bstable/css/bootstrap-table.css"
      rel="stylesheet"
      type="text/css"
    />

    <style>
      .bootstrap-table {
        padding: 20px;
      }

      .dialog-form {
        width: 350px;
      }

      .dialog-form .form_input {
        width: 70%;
      }

      .dialog-form .form-control {
        width: 70%;
        display: inline-block;
      }

      .dialog-form .p_line {
        border: none;
      }
    </style>
  </head>

  <body>
    <div class="tabe_div">
      <p class="p_line text_ient" style="margin-bottom: -10px">
        <a class="find_a">业务小组：</a>
        <select
          class="form_select"
          style="padding-left: 1%"
          id="group"
        ></select>
        <a class="find_a">主管姓名：</a>
        <input
          id="supervisorsName"
          type="text"
          maxlength="8"
          class="form_input text_ient"
          placeholder="请输入主管姓名"
        />
        <a class="find_a">老师姓名：</a>
        <input
          id="teacherName"
          type="text"
          maxlength="11"
          class="form_input text_ient"
          placeholder="请输入老师姓名"
        />
        <input type="button" value="查询" class="but_find" id="search" />
        <input
          type="button"
          value="用户新增"
          onclick="layerOpenUser()"
          class="but_find"
          id="addUser"
        />
        <input
          type="button"
          value="新增业务组"
          onclick="layerOpen(1)"
          class="but_find"
          id="addTeam"
        />
      </p>
      <table
        data-url="json/data_alae_list.json"
        id="table"
        class="table_style"
        style="margin: 0 auto"
      ></table>
    </div>
    <script src="../../../js/jquery.js"></script>
    <script src="../../../js/common.js"></script>
    <script src="../../../js/date/js/laydate.js"></script>
    <script src="../../../bstable/js/bootstrap.min.js"></script>
    <script src="../../../bstable/js/bootstrap-table.js"></script>
    <script src="../../../bstable/js/bootstrap-table-zh-CN.min.js"></script>
    <script src="../../../layer_v2.1/layer/layer.js"></script>
    <script type="text/javascript">
      localStorage.setItem('name', '用户管理/员工管理');

      Date.prototype.Format = function (fmt) {
        // author: meizz
        var o = {
          'M+': this.getMonth() + 1, // 月份
          'd+': this.getDate(), // 日
          'h+': this.getHours(), // 小时
          'm+': this.getMinutes(), // 分
          's+': this.getSeconds(), // 秒
          'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
          S: this.getMilliseconds(), // 毫秒
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            (this.getFullYear() + '').substr(4 - RegExp.$1.length)
          );
        for (var k in o)
          if (new RegExp('(' + k + ')').test(fmt))
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                ? o[k]
                : ('00' + o[k]).substr(('' + o[k]).length)
            );
        return fmt;
      };
      var getTime = function getTime() {
        return new Date().Format('yyyy-MM-dd');
      };

      var getSupervisorNameByTel = function (obj) {
        console.log($(obj).val());
        var val = $(obj).val();
        if (val.length == 11) {
          if (!/^1[3456789]\d{9}$/.test(val)) {
            alert('手机号码有误');
            return false;
          }
          $.ajax({
            url: baseUrl + 'user/getUserInfoByPhone?phone=' + obj.value,
            method: 'GET',
            headers: {
              Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
            },
            success: function (data) {
              if (!data.data.name) {
                $('#zg_name').val('不存在该主管！');
                return false;
              }
              var name = data.data.name;
              window.teacherId = data.data.id;
              $('#zg_name').val(name);
            },
          });
        }
      };

      function createUser() {
        var phone = $('#phone').val();
        var name = $('#name').val();
        var age = $('#age').val();
        var zhiwu = $('#zhiwu').val();
        var pwd = $('#pwd').val();

        if (!phone) {
          return alert('请输入手机号');
        }
        if (!/^1[3456789]\d{9}$/.test(phone)) {
          return alert('请输入正确的手机号');
        }
        if (!name) {
          return alert('请输入姓名');
        }
        // if (!age) {
        //     return alert('请输入年龄');
        // }
        if (!zhiwu) {
          return alert('请选择职务');
        }

        $.ajax({
          type: 'POST',
          url: baseUrl + 'user/register',
          data: {
            mobile: phone,
            realName: name,
            age: age,
            perm: zhiwu,
          },
          headers: {
            Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
          },
          dataType: 'json',
          success: function (data) {
            alert(data.message);
            layer.closeAll();
          },
          error(err) {
            console.log(err.responseText);
            alert(JSON.parse(err.responseText).message);
            layer.closeAll();
          },
        });
      }

      var saveGroup = function saveGroup(type) {
        console.log('新增');
        var formData = new FormData();
        var name = $('#group_name').val();
        var zg_tel = $('#zg_tel').val();
        var zg_name = $('#zg_name').val();
        if (!name) {
          alert('请输入小组名称');
          return false;
        }
        if (!zg_tel) {
          alert('请输入主管电话');
          return false;
        }
        if (!/^1[3456789]\d{9}$/.test(zg_tel)) {
          alert('手机号码有误');
          return false;
        }
        console.log('name:' + name + '  zg_tel:' + zg_tel);
        if (zg_name == '不存在该主管！') {
          alert('该主管不存在，请确认电话号码');
          return false;
        }

        formData.append('businessTeam', name);
        formData.append('teacherId', window.teacherId);
        formData.append('supervisorsName', zg_name);
        formData.append('supervisorsPhone', zg_tel);
        var date = new Date().Format('yyyy-MM-dd');
        formData.append('date', date);
        $.ajax({
          url: baseUrl + 'businessdirector/saveOrUpdate',
          method: 'post',
          headers: {
            Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
          },
          data: formData,
          processData: false,
          contentType: false,
          mimeType: 'multipart/form-data',
          success: function (data) {
            data = JSON.parse(data);
            if (data.code == 500) {
              alert(data.message);
              // layer.msg(data.message);
              layer.closeAll();
            } else {
              alert('保存成功');
              layer.closeAll();
            }
            // $('#table').bootstrapTable("refresh");
          },
        });
      };

      function layerOpenUser() {
        var html = `<div class="dialog-form"><div class="p_line text_ient lx-row">
                            <p class="col lx-col-50">
                    <a class="find_a">手机：&nbsp;</a>
                    <input id="phone" type="text" maxlength="11" style="width: 66%;" class="form_input text_ient" placeholder="请输入手机"/>
                </p>
                            <p class="col lx-col-50">
                    <a class="find_a">姓名：&nbsp;</a>
                    <input id="name" type="text" maxlength="11" style="width: 66%;" class="form_input text_ient" placeholder="请输入姓名"/>
                </p>
                            <p class="col lx-col-50">
                    <a class="find_a">年龄：&nbsp;</a>
                    <input id="age" type="text" maxlength="11" style="width: 66%;" class="form_input text_ient" placeholder="请输入年龄"/>
                </p>
                            <p class="col lx-col-50">
                                <a class="find_a">职务：</a>
            <select id="zhiwu" class="form_input">
                <option value="2">教务主管</option>
                <option value="21">教务(学历教育)</option>
                <option value="22">教务(课程培训)</option>
                <option value="23">教务(职业资格)</option>
                <option value="24">教务(职称评审)</option>
                <option value="3">财务</option>
                <option value="4">招生老师</option>
                <option value="5">业务主管</option>
            </select>
                </p>
            </div></div>`;

        layer.open({
          title: '创建用户',
          type: 1,
          // closeBtn: 0, //不显示关闭按钮
          anim: 2,
          yes: function (index, layero) {
            createUser();

            //do something
            // console.log(index, layero);
            // layer.close(index); //如果设定了yes回调，需进行手工关闭
          },
          btn: ['保存'],
          // shadeClose: true, //开启遮罩关闭
          content: html,
        });
      }

      function layerOpen(type) {
        var html = `<div class="dialog-form"><div class="p_line text_ient lx-row">
                            <p class="col lx-col-50">
                    <a class="find_a">创建时间：</a>
                    ${getTime()}
                </p>
                            <p class="col lx-col-50">
                    <a class="find_a">业务小组：&nbsp;</a>
                    <input id="group_name" type="text" maxlength="11" style="width: 66%;" class="form_input text_ient" placeholder="请输入名称"/>
                </p>
                <p class="col lx-col-50">
                    <a class="find_a">
                        主管手机号：</a>
                    <input id="zg_tel" type="text" maxlength="11" style="width: 66%;" class="form_input text_ient" placeholder="请输入11位手机号" oninput="getSupervisorNameByTel(this)"/>
                </p>
                <p class="col lx-col-50">
                    <a class="find_a">
                        主管姓名：&nbsp;</a>
                    <input id="zg_name" type="text" maxlength="10" class="form_input text_ient" placeholder="主管姓名" disabled/>
                </p>
            </div></div>`;

        layer.open({
          title: '创建业务组',
          type: 1,
          // closeBtn: 0, //不显示关闭按钮
          anim: 2,
          yes: function (index, layero) {
            saveGroup(type);

            //do something
            // console.log(index, layero);
            // layer.close(index); //如果设定了yes回调，需进行手工关闭
          },
          btn: ['保存'],
          // shadeClose: true, //开启遮罩关闭
          content: html,
        });
      }

      function changeFee(ids) {
        var arr = ids.split(',');
        $.ajax({
          url: baseUrl + 'studentInfo/setStudentFeeFlag',
          method: 'get',
          headers: {
            Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
          },
          data: {
            studentId: arr[0],
            feeId: arr[1],
            feeFlag: arr[2],
          },
          success: function (data) {
            $('#table').bootstrapTable('refresh');
            alert('操作成功');
          },
          error() {
            alert('操作失败');
          },
        });
      }
      $(function () {
        $('#search').on('click', function () {
          $('#table').bootstrapTable('refresh');
        });
        $('#table').bootstrapTable({
          method: 'get',
          striped: true,
          singleSelect: false,
          url: baseUrl + 'businessdirectorteacher/getTeacherList',
          dataType: 'json',
          sidePagination: 'server',
          pagination: true, //分页
          pageSize: 10,
          pageNumber: 1,
          // rowStyle: rowStyle,
          search: false, //显示搜索框
          contentType: 'application/x-www-form-urlencoded',
          ajaxOptions: {
            headers: {
              Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
            },
          },
          queryParams: function (params) {
            params.businessTeam = $('#group').val() ? $('#group').val() : '';
            params.supervisorsName = $('#supervisorsName').val().trim();
            params.teacherName = $('#teacherName').val().trim();
            params.offset = params.offset / params.limit;
            params.page = parseInt(params.offset) + 1;
            delete params.order;
            console.log(params);
            return params;
          },
          responseHandler: function (res) {
            console.log(res);
            var list = res.data.result.records;

            return {
              rows: list,
              total: res.data.total,
            };
          },
          columns: [
            {
              field: 'no',
              title: '序号',
              sortable: true,
              align: 'center',
              formatter: function (value, row, index) {
                var pageSize =
                  $('#table').bootstrapTable('getOptions').pageSize;
                var pageNumber =
                  $('#table').bootstrapTable('getOptions').pageNumber;
                return pageSize * (pageNumber - 1) + index + 1;
              },
            },
            {
              title: '业务小组',
              field: 'businessTeam',
              align: 'center',
              valign: 'middle',
            },
            {
              title: '主管姓名',
              field: 'supervisorsName',
              align: 'center',
            },
            {
              title: '老师姓名',
              field: 'teacherName',
              align: 'center',
            },
            {
              title: '老师手机号',
              field: 'mobile',
              align: 'center',
            },
            {
              title: '角色',
              field: 'permString',
              align: 'center',
            },
            {
              title: '状态',
              field: 'flag',
              align: 'center',
              formatter: function (value, row, index) {
                return value == '0' ? '封存' : '正常';
              },
            },
            {
              title: '创建日期',
              field: 'createDate',
              align: 'center',
            },
            {
              title: '操作',
              field: 'id',
              align: 'center',
              width: '160',
              formatter: function (value, row) {
                var e =
                  '<a href="#" onclick="config(\'' +
                  row.businessDirectorTeacherId +
                  "', '" +
                  row.teacherId +
                  "', '" +
                  row.businessTeam +
                  "', '" +
                  row.mobile +
                  "', '" +
                  row.teacherName +
                  "','" +
                  row.createDate +
                  "','" +
                  row.perm +
                  "','" +
                  row.userId +
                  '\')">编辑</a>&nbsp;&nbsp;&nbsp;';
                var f = `<a href="#" onclick="disable('${row.userId}', 0)">封存</a>`;
                var g = `<a href="#" onclick="disable('${row.userId}', 1)">启用</a>`;
                var h = `&nbsp;&nbsp;&nbsp;<a href="#" onclick="reset('${row.userId}', 1)">重置密码</a>`;

                return e + (row.flag == '0' ? g : f) + h;
              },
            },
          ],
        });
      });
      queryGroup();

      //查询业务小组
      function queryGroup(eleId, val) {
        $.ajax({
          url: baseUrl + 'businessdirector/listAll',
          method: 'Post',
          headers: {
            Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
          },
          data: '',
          success: function (data) {
            var html_ = '<option value="">请选择</option>';
            for (var i = 0; i < data.data.length; i++) {
              var item = data.data[i];
              html_ +=
                '<option  value="' +
                item.id +
                '" >' +
                item.businessTeam +
                '</option>';
            }
            if (!eleId) {
              $('#group').html(html_);
            } else {
              $('#' + eleId).html(html_);
              $('#' + eleId)
                .find('option:contains(' + val + ')')
                .attr('selected', true);
            }
          },
        });
      }

      /**
       * 修改老师
       */
      function updateTeacher(id, teacherId, userId, perm) {
        var formData = new FormData();
        var businessId = $('#group_name').val();
        var teacher_tel = $('#teacher_num').val();
        var teacher_name = $('#teacher_name').val();
        var roleId = $('#zhiwu-edit').val();
        console.log(`roleId`, roleId);

        if (!businessId || businessId == 0) {
          alert('请选择小组');
          return false;
        }

        if (!teacher_name) {
          alert('请输入老师名称');
          return false;
        }

        if (id) {
          formData.append('id', id);
        }

        formData.append('businessId', businessId);
        formData.append('teacherId', teacherId);
        formData.append('teacherName', teacher_tel);
        formData.append('mobile', teacher_name);
        formData.append('userId', userId);
        formData.append('roleId', roleId);
        formData.append('isUpdateRole', perm != roleId);
        $.ajax({
          url: baseUrl + 'businessdirectorteacher/updateOrSave',
          method: 'post',
          headers: {
            Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
          },
          data: formData,
          processData: false,
          contentType: false,
          mimeType: 'multipart/form-data',
          success: function (data) {
            const newData = JSON.parse(data);
            if (newData.code == 201) {
                alert(newData.message);
                return;
            }
            layer.closeAll();
            alert('保存成功');
            // layer.msg('保存成功');
            $('#table').bootstrapTable('refresh');
          },
        });
      }

      function disable(userId, flag) {
        $.ajax({
          url: baseUrl + `user/lock?userId=${userId}&flag=${flag}`,
          method: 'post',
          headers: {
            Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
          },
          // data: formData,
          processData: false,
          contentType: false,
          success: function (data) {
            alert(data.data || '操作失败');
            // layer.msg('保存成功');
            $('#table').bootstrapTable('refresh');
          },
        });
      }

      function reset(userId) {
        $.ajax({
          url: baseUrl + `user/reset?userId=${userId}`,
          method: 'post',
          headers: {
            Authorization: JSON.parse(localStorage.getItem('userInfo')).token,
          },
          // data: formData,
          processData: false,
          contentType: false,
          success: function (data) {
            alert(data.data || '操作失败');
            // layer.msg('保存成功');
            $('#table').bootstrapTable('refresh');
          },
        });
      }

      function config(
        id,
        teacherId,
        businessTeam,
        teacherPhone,
        teacherName,
        createDate,
        perm,
        userId
      ) {
        queryGroup('group_name', businessTeam);
        // console.log("row:" + row.toString());
        layer.open({
          title: '招生老师管理',
          offset: 't',
          type: 1,
          // closeBtn: 0, //不显示关闭按钮
          anim: 2,
          yes: function (index, layero) {
            //do something
            updateTeacher(id, teacherId, userId, perm);
            // layer.msg('保存成功');
            // console.log(index, layero);
            // layer.close(index); //如果设定了yes回调，需进行手工关闭
          },
          btn: ['修改'],
          // shadeClose: true, //开启遮罩关闭
          content: `<div class="dialog-form"><div class="p_line text_ient lx-row">
                            <p class="col lx-col-50">
                    <a class="find_a">业务小组：</a>
                    <select id="group_name" class="form_select" style="padding-left: 1%;">
                    </select>
                </p>
                <p class="col lx-col-50">
                    <a class="find_a">
                        老师姓名：</a>
                    <input id="teacher_num" type="text" maxlength="10" style="width: 66%;" class="form_input text_ient" placeholder="" value="${teacherName}"/>
                </p>
                <p class="col lx-col-50">
                    <a class="find_a">
                        老师手机号：</a>
                    <input id="teacher_name" type="text" maxlength="11" style="width: auto;" class="form_input text_ient" placeholder="" value="${teacherPhone}"/>
                </p>
                <p class="col lx-col-50">
                    <a class="find_a">
                        角色：</a>
                        <select id="zhiwu-edit" class="form_select" style="padding-left: 1%;">
                            <option value="2" ${perm == 2 ? 'selected' : ''}>教务主管</option>
                <option value="21" ${perm == 21 ? 'selected' : ''}>教务(学历提升)</option>
                <option value="22" ${perm == 22 ? 'selected' : ''}>教务(执业资格)</option>
                <option value="23" ${perm == 23 ? 'selected' : ''}>教务(职业技能)</option>
                <option value="24" ${perm == 24 ? 'selected' : ''}>教务(职称评审)</option>
                <option value="3" ${perm == 3 ? 'selected' : ''}>财务</option>
                <option value="4" ${perm == 4 ? 'selected' : ''}>招生老师</option>
                <option value="5" ${perm == 5 ? 'selected' : ''}>业务主管</option>
                    </select>
                </p>
            </div></div>`,
        });
      }

      function rowStyle(item, index) {
        style = item.colorFlag == 1 ? { css: { color: '#ed5565' } } : {};
        return style;
      }
    </script>
  </body>
</html>
